package lx.exalarm.activity;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;

import java.io.IOException;

import lx.exalarm.alarm.ActionBean;
import lx.exalarm.base.BaseSimplePlayActivity;
import lx.exalarm.utils.log.Log;

/**
 * Created by liuxu on 15-3-3.
 */
public class ActivityPlayAudio extends BaseSimplePlayActivity {

    private MediaPlayer mMediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopMusic();
    }

    @Override
    protected void init(ActionBean action, ActionBean next) {

    }

    @Override
    protected void startAction(ActionBean action) {
        startAnim();
        if (action == null || action.getData() == null) {
            Log.e("can not play audio, data null");
            return;
        }
        Uri uri = Uri.parse(action.getData());
        startMusic(uri);
    }

    @Override
    protected void stopAction(ActionBean action) {
        stopMusic();
        startAnim();
    }

    private void startMusic(Uri uri) {
        if (mMediaPlayer != null) {
            mMediaPlayer.reset();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);

        try {
            mMediaPlayer.setDataSource(this, uri);
            mMediaPlayer.setLooping(true);
            mMediaPlayer.prepare();
        } catch (IOException e) {
            Log.e("can not play audio, data invalid", e);
            Toast.makeText(this, "fail to play music", Toast.LENGTH_LONG).show();
            return;
        }

        if(!mMediaPlayer.isPlaying()) {
            mMediaPlayer.start();
        }
    }

    private void stopMusic() {
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }

}
